
// api接口使用的加密方法，返回加密后的字符串。秘钥为硬编码
export function ApiEncrypt (planeText) {
  var resultString = ''
  if (planeText.length > 0) {
    // 秘钥
    var keyString = '36095106549644D4FB0A0B0246BD0F880BEA088'
    // 明文长度
    var planeTextLength = planeText.length
    // 明文长度与秘钥长度之差
    var diffLength = planeTextLength - keyString.length
    // 明文多的部分补P
    if (diffLength > 0) {
      keyString = keyString.padEnd(planeText.length, 'P')
    }
    for (var i = 0; i < planeTextLength; i++) {
      var ch = planeText.substring(i, i + 1)
      var ky = keyString.substring(i, i + 1)
      var chn = ch.charCodeAt(0) + ky.charCodeAt(0) - 48
      resultString = resultString + chn.toString(16)
    }
    console.log(resultString.toUpperCase())
  }
  return resultString.toUpperCase()
}
// 16进制转字符串
export function hexCharCodeToStr (hexCharCodeStr) {
  var trimedStr = hexCharCodeStr.trim()
  var rawStr = trimedStr.substr(0, 2).toLowerCase() === '0x' ? trimedStr.substr(2) : trimedStr
  var len = rawStr.length
  if (len % 2 !== 0) {
    alert('Illegal Format ASCII Code!')
    return ''
  }
  var curCharCode
  var resultStr = []
  for (var i = 0; i < len; i = i + 2) {
    curCharCode = parseInt(rawStr.substr(i, 2), 16)// ASCII Code Value
    resultStr.push(String.fromCharCode(curCharCode))
  }
  return resultStr.join('')
}
// api接口使用的解密方法，返回解密的字符串。秘钥为硬编码
export function ApiDecryptString (cipherText) {
  var resultString = ''
  if (cipherText.length > 0) {
    var keyString = '36095106549644D4FB0A0B0246BD0F880BEA088'
    var keyCharString = hexCharCodeToStr(cipherText)
    console.log('keyCharString*' + keyCharString)
    var diffLength = keyCharString.length - keyString.Length
    if (diffLength > 0) {
      keyString = keyString.padEnd(keyCharString.length, 'P')
    }
    for (var i = 0; i < keyCharString.length; i++) {
      var ch = keyCharString.substring(i, i + 1)
      var ky = keyString.substring(i, i + 1)
      var chn = ch.charCodeAt(0) - ky.charCodeAt(0) + 48
      // 数字转为对应的asc码
      var chnChar = String.fromCharCode(chn)
      resultString = resultString + chnChar.toString()
    }
  }
  return resultString
}
